import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {QuestionDto} from './dto/question.dto'
import { Question} from './entities/question.entity'
@Injectable()
export class QuestionService {
  constructor(
    @InjectModel('Questions') private readonly questionModel:Model<Question>
) {}
  async create(questionDto: QuestionDto) {
    return await this.questionModel.insertMany(questionDto);
  }

  async findAll():Promise<QuestionDto[]> {
    return await this.questionModel.find().exec();
  }

  async findOne(issues: string, id: string):Promise<QuestionDto[]> {
    if(id)return await this.questionModel.find({_id:id});
    if(issues)return await this.questionModel.find({issues:{$regex:issues}});
  }

  async update(id: string, questionDto: QuestionDto) {
    return await this.questionModel.updateOne({_id:id}, questionDto);
  }

  async remove(id: string):Promise<any> {
    return await this.questionModel.deleteOne({_id:id});
  }

  async list(page: number, pageSize: number, userId: string):Promise<any> {
    const skip = (page - 1) * pageSize;
    const data = await this.questionModel.find({userId:userId}).sort({ time: -1 })
    const list = await this.questionModel.find({userId:userId}).sort({ time: -1 }).skip(skip).limit(pageSize)
    return {total: data.length, list: list}
  }
}
